﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Security.Cryptography;

using Gift.Model;
using Gift.DAL;
using Gift.Security;

namespace WebSite.admin.product
{
    public partial class SendGSM : BaseAdmin
    {
        sms.WebService theSMS = new sms.WebService();
        string sn = System.Configuration.ConfigurationManager.AppSettings["GMSSN"];// "SDK-BBX-010-13406";//序列号
        string password = System.Configuration.ConfigurationManager.AppSettings["GMSPas"];//"413717";//密码
        string mobile = "";//手机
        string cont = "";//内容
        string subcode = "";//扩展码
        string stime = "";//定时时间

        string sContentFormat = "阳澄湖牌提醒：您的{0}送您一份{1}元的{2}礼品卡,卡号：{3}，密码：{4}；请到www.haolicard.com兑换,您也可登录手机站点m.temall.com兑换。";


        Card theCard = new Card();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.txtSender.Text = base.AdminUser;
                BindGridView();
            }
        }

        protected void btnSend_Click(object sender, EventArgs e)
        {
            this.tdResult.InnerHtml = string.Empty;
            //获取参数
            getValues();
            //MD5加密密码
            string pwd = getMD5(sn + password);

            long startTime, endTime;
            startTime = DateTime.Now.Ticks;//记录当前时刻

            //发送短信
            //定时时间，扩展码和rrid可以为空，当rrid(唯一标识串)为空时，返回系统指定rrid
            string result =  theSMS.mt(sn, pwd, mobile, cont, subcode, stime, "");

            endTime = DateTime.Now.Ticks;
            TimeSpan sendSpan = new TimeSpan(endTime - startTime);
            StringBuilder sbOutput = new System.Text.StringBuilder();
            if (result.StartsWith("-"))
            {
                sbOutput.Append(result + "\r");
            }
            else
            {
                string sSQLInsert = "insert into tbGMS(CardId,SendDate,AdminId,AdminName,ReceiveMobile,Receiver)"
                                 + " values({0},'{1}',{2},'{3}','{4}','{5}');";

                SQLAccess.DoSql(string.Format(sSQLInsert
                                              ,Request.QueryString["cardid"],DateTime.Now.ToString(),base.AdminUserId,this.txtSender.Text.Trim()
                                              ,this.txtMobile.Text.Trim(),txtReciver.Text.Trim()));
                sbOutput.Append("发送成功" + "\r");
                sbOutput.Append("发送用时" + sendSpan.ToString() + "s\r");
            }
            this.tdResult.InnerHtml = sbOutput.ToString();
            this.BindGridView();
            this.txtMobile.Text = string.Empty;
            this.txtConfirmMobile.Text = string.Empty;
            this.txtReciver.Text = string.Empty;
        }

        /// <summary>
        /// 获取参数
        /// </summary>
        private void getValues()
        {
            mobile = txtMobile.Text.Trim();
           // subcode = tex_subcode.Text;
           // sn = tex_sn.Text.Trim();
            //password = tex_pwd.Text.Trim();
            //if (sch_time.Enabled)
            //{
            //    //取得定时时间
            //    stime = sch_time.Text;
            //}

            dbCard oCard = theCard.GetModel(int.Parse(Request.QueryString["cardid"]));
            cont = string.Format(sContentFormat
                                  , txtRelation.Text.Trim() + txtSender.Text.Trim()
                                   ,oCard.cardprice.ToString()
                                   ,oCard.ProfessionTypeName
                                   ,oCard.cardcode
                                   ,DESEncrypt.Decrypt(oCard.cardpas));
                                   
        }

        /// <summary>
        /// 获取md5码
        /// </summary>
        /// <param name="source">待转换字符串</param>
        /// <returns>md5加密后的字符串</returns>
        public string getMD5(string source)
        {
            string result = "";
            try
            {
                MD5 getmd5 = new MD5CryptoServiceProvider();
                byte[] targetStr = getmd5.ComputeHash(UnicodeEncoding.UTF8.GetBytes(source));
                result = BitConverter.ToString(targetStr).Replace("-", "");
                return result;
            }
            catch (Exception)
            {
                return "0";
            }

        }

        private void BindGridView()
        {
            DataSet ds = SQLAccess.GreatDs("select *,(select cardcode from db_Card where cardid=" +  Request.QueryString["cardid"] +") as cardcode from tbGMS where CardId = " + Request.QueryString["cardid"]);
            this.gvInfo.DataSource = ds;
            this.gvInfo.DataBind();
        }
    }
}